#if ANDROID
using Android.Content;
using RadioTimer.Services;

namespace RadioTimer.Services
{
    public class ForegroundServicePlatform : IForegroundService
    {
        private bool _isRunning = false;

        public bool IsRunning => _isRunning;

        public event EventHandler<string>? StatusChanged;

        public async Task StartAsync()
        {
            try
            {
                if (_isRunning) return;

                var context = Platform.CurrentActivity ?? Android.App.Application.Context;
                var serviceIntent = new Intent(context, typeof(Platforms.Android.ForegroundService));
                
                if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.O)
                {
                    context.StartForegroundService(serviceIntent);
                }
                else
                {
                    context.StartService(serviceIntent);
                }

                _isRunning = true;
                StatusChanged?.Invoke(this, "服务已启动");
            }
            catch (Exception ex)
            {
                Services.DebugLogger.WriteError($"Error starting foreground service: {ex.Message}");
                StatusChanged?.Invoke(this, $"启动服务失败: {ex.Message}");
            }
        }

        public async Task StopAsync()
        {
            try
            {
                if (!_isRunning) return;

                var context = Platform.CurrentActivity ?? Android.App.Application.Context;
                var serviceIntent = new Intent(context, typeof(Platforms.Android.ForegroundService));
                context.StopService(serviceIntent);

                _isRunning = false;
                StatusChanged?.Invoke(this, "已停止服务");
            }
            catch (Exception ex)
            {
                Services.DebugLogger.WriteError($"Error stopping foreground service: {ex.Message}");
                StatusChanged?.Invoke(this, $"停止服务失败: {ex.Message}");
            }
        }
    }
}
#else
namespace RadioTimer.Services
{
    public class ForegroundServicePlatform : IForegroundService
    {
        public bool IsRunning => false;

        public event EventHandler<string>? StatusChanged;

        public Task StartAsync()
        {
            StatusChanged?.Invoke(this, "此平台不支持前台服务");
            return Task.CompletedTask;
        }

        public Task StopAsync()
        {
            StatusChanged?.Invoke(this, "此平台不支持前台服务");
            return Task.CompletedTask;
        }
    }
}
#endif